<?php
declare (strict_types=1);

namespace app\user\logic\user\admin;

use app\common\exception\LogicException;
use app\user\model\user\admin\Credit as CreditModel;

/**
 * Class Credit
 *
 * @package app\user\logic\user\admin
 */
class Credit extends CreditModel
{
    /**
     * 系统增加积分
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-04-21
     */
    public function increaseUserCredit($uid, $num)
    {
        $this->startTrans();
        try {
            $credit = $this->where('user_id', $uid)->findOrEmpty();
            if ($credit->isEmpty()) {
                // 添加余额
                $credit          = new CreditModel();
                $credit->user_id = $uid;
                $credit->credit  = $num;
                if (!$credit->save()) {
                    throw new LogicException('用户积分变更失败');
                }
            } else {
                // 变更余额
                $credit->credit += $num;
                $credit->save();
            }
            // 流水记录
            app(CreditFlow::class)->updateFlow($uid, 9, $num, $credit->credit, 0, 0, '系统增加');
            $this->commit();
        } catch (LogicException $e) {
            $this->rollback();
            throw new LogicException('用户余额变更失败');
        }

        return $credit;
    }

    /**
     * 系统扣除积分
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-04-21
     */
    public function decreaseUserCredit($uid, $num)
    {
        $this->startTrans();
        try {
            $info = $this->where('user_id', $uid)->findOrEmpty();
            // 积分不足
            if ($info->isEmpty() || $info->credit < $num) {
                throw new LogicException('当前用户积分不足');
            }
            // 变更余额
            $info->credit -= $num;
            $info->save();
            // 流水记录
            app(CreditFlow::class)->updateFlow($uid, 10, $num, $info->credit, 0, 0, '系统扣除');
            $this->commit();
        } catch (LogicException $e) {
            $this->rollback();
            throw new LogicException($e->getMessage());
        }

        return $info;
    }

    /**
     * 设置用户积分
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/9/8
     *
     * @param int $userId
     * @param     $balance
     * @return Balance|array|\think\Model|null
     */
    public function setUserCredit(int $userId, $credit)
    {
        $data = $this->where('user_id', $userId)->findOrEmpty();
        if ($data->isEmpty() || $data->credit < $credit) {
            $num = $credit - $data->credit;
            return $this->increaseUserCredit($userId, $num);
        } else if ($data->credit > $credit) {
            $num = $data->credit - $credit;
            return $this->decreaseUserCredit($userId, $num);
        }

        throw new LogicException('未做任何操作');
    }

}